<?php

namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Models\Admin\AdminBonusLog;
use App\Models\Admin\AdminUser;
use App\Models\Admin\AfterSale;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AftersaleController extends BaseController
{
    protected $fields = array(
        'after_sale_id' => '',
        'goods_name' => '',
        'goods_money' => 0,
        'order_number' => '',
        'buy_time' => '',
        'buy_length' => 0,
        'member_name' => '',
        'member_phone' => '',
        'sbr_id' => 0,
        'after_type' => 1,
        'after_money' => 0,
        'remarks' => ''
    );

    public function __construct(Request $request){
        parent::__construct($request);
    }

    /* 售后订单列表 */
    public function dataList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $page_no = $request->post('page_no', 1);
        $page_size = $request->post('page_size', 10);
        $searchFilter = array(
            'sortName' => $request->post('sortName','id'),                                                  //排序列名
            'sortOrder' => $request->post('sortOrder','desc'),                                              //排序（desc，asc）
            'pageNumber' => $page_no,                                                                                   //当前页码
            'pageSize' => $page_size,                                                                                   //一页显示的条数
            'start' => ($page_no-1) * $page_size,                                                                       //开始位置
            'searchKey' => trim($request->post('search','')),                                               //搜索关键词
            'start_time' => trim($request->post('start_time','')),                                          //订单创建时间(开始)
            'end_time' => trim($request->post('end_time','')),                                              //订单创建时间(结束)
            'branch_id' => trim($request->post('branch_id','')),                                            //团队ID
            'user_id' => trim($request->post('user_id','')),                                                //销售ID
            'after_status' => trim($request->post('status','')),                                            //业绩订单状态
//            'number_sn' => trim($request->post('number_sn','')),                                            //业绩订单号
            'admin_id' => $this->AU['position'] == "超级管理员" ? "" : $this->AU['id'],
            'is_del' => 0
        );
        $afterSaleModel = new AfterSale();
        $list = $afterSaleModel->getAfterSaleList($searchFilter);
        $list['rows'] = $afterSaleModel->buildAfterSaleListFields($list['rows'],trim($request->post('surplus_time','')));
        $this->returnData['data'] = $list;
        return $this->return_result($this->returnData);
    }

    /* 售后订单详情 */
    public function detail(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $id = $request->id;
        $afterSaleModel = new AfterSale();
        $data = $afterSaleModel->getAfterSaleOrderByID((int)$id);
        if (!$data){
            $this->returnData = ErrorCode::$admin_enum['not_exist'];
            return $this->return_result($this->returnData);
        }
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    /* 添加售后订单 */
    public function create(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $after_sale = [];
        foreach (array_keys($this->fields) as $field) {
            /* 验证参数未做 */
            $after_sale[$field] = $request->post($field,$this->fields[$field]);
        }
        $afterSaleModel = new AfterSale();
        $res = $afterSaleModel->afterSaleInsert($after_sale, $this->AU['name']);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '添加失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '添加成功';
        return $this->return_result($this->returnData);
    }

    /* 售后修改 */
    public function edit(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $id = $request->id;
        $after_sale = [];
        foreach (array_keys($this->fields) as $field) {
            /* 验证参数未做 */
            if($request->post($field)===NULL){
                continue;
            }
            $after_sale[$field] = $request->post($field,$this->fields[$field]);
        }
        $afterSaleModel = new AfterSale();
        $data = $afterSaleModel->getAfterSaleOrderByID((int)$id);
        if (!$data){
            $this->returnData = ErrorCode::$admin_enum['not_exist'];
            return $this->returnData;
        }
        $afterSaleModel = new AfterSale();
        $res = $afterSaleModel->afterSaleUpdate((int)$id,$after_sale);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '修改失败';
            return $this->returnData;
        }
        $this->returnData['msg'] = '修改成功';
        return $this->returnData;
    }

    //售后转移
    public function exchangeOrder(Request $request) {
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$touid = $request->exchange_user){
            return ErrorCode::code("params_not_exist", "接受人ID");
        }
        if(!$orderList = $request->exchange_list){
            return ErrorCode::code("params_not_exist", "转移订单");
        }
        $orderList = (array)@json_decode($orderList,true);
        if(empty($orderList)){
            return ErrorCode::code("customized", "转移订单参数错误");
        }
        $count = count($orderList);
        DB::beginTransaction();
        $adminBonusModel = new AdminBonusLog();
        foreach ($orderList as $id){
            if($id && !empty($afterSaleData = AfterSale::query()->where(["id" => $id, "mall_id" => $request->mallData['id'], "after_status" => 0])->first())){
                if($afterSaleData['after_sale_id'] == $touid){
                    if($count == 1){
                        return ErrorCode::code("customized", "不能转移给自己");
                    }
                    continue;
                }
                $bonus = sprintf("%.2f", $afterSaleData->bonus_royalty / $afterSaleData->buy_length * $afterSaleData->after_time);
                if(!AfterSale::query()->where("id", $id)->update(["after_status" => 1, "shift_status" => 1, "remarks" => "售后单转出", "bonus_royalty" => $bonus])){
                    DB::rollBack();
                    return ErrorCode::code("customized", "转出售后单失败");
                }
                $newBonus = $afterSaleData['bonus_royalty'] - $bonus;
                // 记录流水
                $data_ins['admin_users_id'] = $afterSaleData['after_sale_id'];
                $data_ins['type'] = 9; // 减少奖金
                $data_ins['money'] = -$newBonus;
                $data_ins['cur_bonus'] = AdminUser::query()->where("id", $afterSaleData['after_sale_id'])->value("sale_bonus");
                $data_ins['member_name'] = $afterSaleData->member_name;
                $data_ins['member_phone'] = $afterSaleData->member_phone;
                $data_ins['goods_name'] = $afterSaleData->goods_name;
                $data_ins['goods_money'] = $afterSaleData->goods_money;
                $data_ins['order_number'] = $afterSaleData->order_number;
                $data_ins['number_sn'] = $afterSaleData->number_sn;
                $data_ins['remarks'] = '售后单转出';
                $data_ins['submitter'] = AdminUser::query()->where("id", $this->AU['id'])->value("name");
                $data_ins['auditor'] = $this->AU['name'];
                if(!$adminBonusModel->adminBonusLogInsert($data_ins)){
                    DB::rollBack();
                    return ErrorCode::code("customized", "转出流水记录失败");
                }
                // 更新售后人员钱包
                AdminUser::query()->where("id", $afterSaleData['after_sale_id'])->update(["sale_bonus" => $data_ins['cur_bonus'] - $newBonus]);
                $afterSaleData = $afterSaleData->toArray();
                unset($afterSaleData['id'], $afterSaleData['updated_at']);
                $afterSaleData = array_merge($afterSaleData, [
                    "after_sale_id" => $touid, //"buy_length" => $afterSaleData['buy_length'] - $afterSaleData['after_time'], "after_time" => 0,
                    "after_money" => 0, "shift_status" => 2, "remarks" => "售后单转入", "created_at" => Carbon::now()->toDateTimeString(),
                    "bonus_royalty" => $newBonus, "after_status" => 2
                ]);
                if(!AfterSale::query()->insert($afterSaleData)){
                    DB::rollBack();
                    return ErrorCode::code("customized", "转入售后单失败");
                }
            }
        }
        DB::commit();
        $this->returnData['msg'] = "修改成功";
        return $this->return_result($this->returnData);
    }

    public function verifyOrder(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->id){
            return ErrorCode::code("params_not_exist", "售后单ID");
        }
        if(!$request->status){
            return ErrorCode::code("params_not_exist", "状态");
        }
        if($request->status == 'agree') {
            $afterSaleData = AfterSale::query()->where(["id" => $request->id, "mall_id" => $request->mallData['id'], "after_status" => 3])->first();
            if (empty($afterSaleData)) {
                return ErrorCode::code("params_not_exist", "售后单不存在");
            }
            // 记录流水
            $data_ins['member_name'] = $afterSaleData->member_name;
            $data_ins['member_phone'] = $afterSaleData->member_phone;
            $data_ins['goods_name'] = $afterSaleData->goods_name;
            $data_ins['goods_money'] = $afterSaleData->goods_money;
            $data_ins['order_number'] = $afterSaleData->order_number;
            $data_ins['number_sn'] = $afterSaleData->number_sn;
            $data_ins['submitter'] = AdminUser::query()->where("id", $this->AU['id'])->value("name");
            $data_ins['auditor'] = $this->AU['name'];
            $data_ins['admin_users_id'] = $afterSaleData->after_sale_id;
            $data_ins['type'] = 4; // 增加奖金
            $data_ins['money'] = $afterSaleData->bonus_royalty;
            $data_ins['cur_bonus'] = AdminUser::query()->where("id", $afterSaleData->after_sale_id)->value("sale_bonus");
            $data_ins['remarks'] = '售后单转入';
            $adminBonusModel = new AdminBonusLog();
            if (!$adminBonusModel->adminBonusLogInsert($data_ins)) {
                return ErrorCode::code("customized", "转入流水记录失败");
            }
            // 更新售后人员钱包
            AdminUser::query()->where("id", $afterSaleData->after_sale_id)->update(["sale_bonus" => $data_ins['cur_bonus'] + $afterSaleData->bonus_royalty]);
            AfterSale::query()->where("id", $request->id)->update(["after_status" => 0]);
            $this->returnData['msg'] = "审核成功";
        }else{
            AfterSale::query()->where("id", $request->id)->update(["after_status" => 2]);
            $this->returnData['msg'] = "拒绝成功";
        }
        return $this->return_result($this->returnData);
    }

    /* 售后订单操作 */
    public function ajax(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if (!isset($request->action) || !in_array(strval($request->action),['prohibit','open'],true)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            return $this->return_result($this->returnData);
        }
        $id = $request->id;
        //更新订单状态
        if($request->action == 'prohibit'){
            $afterSaleModel = new AfterSale();
            $flag = $afterSaleModel->afterSaleUpdateByFields($id,['after_status'=>1]);
            if(!$flag){
                $this->returnData = ErrorCode::$admin_enum['fail'];
                $this->returnData['msg'] = '禁用失败';
                return $this->return_result($this->returnData);
            }
            $afterSaleData = AfterSale::query()->where("id", $id)->first();
            if($afterSaleData->bonus_royalty > 0){
                $bonus_money = $afterSaleData->bonus_royalty - sprintf("%.2f", $afterSaleData->bonus_royalty / $afterSaleData->buy_length * $afterSaleData->after_time);
                if($bonus_money > 0) {
                    // 更新奖金
                    if (!AdminUser::query()->where("id", $afterSaleData->after_sale_id)->update(["sale_bonus" => DB::raw("sale_bonus-{$bonus_money}")])) {
                        return ErrorCode::code("customized", '更新用户销售奖金失败');
                    } else {
                        //业绩流水表
                        $data_ins['admin_users_id'] = $afterSaleData->after_sale_id;
                        $data_ins['type'] = 9; // 减少奖金
                        $data_ins['money'] = -$bonus_money;
                        $data_ins['cur_bonus'] = AdminUser::query()->where("id", $afterSaleData->after_sale_id)->value("sale_bonus");
                        $data_ins['member_name'] = $afterSaleData->member_name;
                        $data_ins['member_phone'] = $afterSaleData->member_phone;
                        $data_ins['goods_name'] = $afterSaleData->goods_name;
                        $data_ins['goods_money'] = $afterSaleData->goods_money;
                        $data_ins['order_number'] = $afterSaleData->order_number;
                        $data_ins['number_sn'] = $afterSaleData->number_sn;
                        $data_ins['remarks'] = $afterSaleData->remarks;
                        $data_ins['submitter'] = $this->AU['name'];
                        $data_ins['auditor'] = $this->AU['name'];
                        $data_ins["mall_id"] = request()->mallData["id"];
                        $adminBonusModel = new AdminBonusLog();
                        $adminBonusModel->adminBonusLogInsert($data_ins);
                    }
                    // 更新售后单
                    if (!AfterSale::query()->where("id", $afterSaleData->id)->update(["bonus_royalty" => DB::raw("bonus_royalty-{$bonus_money}"), "after_status" => 1])) {
                        return ErrorCode::code("customized", '更新售后单失败');
                    }
                }
            }
            $this->returnData['msg'] = '禁用成功';
            return $this->return_result($this->returnData);
        }
        $this->returnData = ErrorCode::$admin_enum['fail'];
        $this->returnData['msg'] = '未知操作';
        return $this->return_result($this->returnData);
    }

    //删除售后订单
    public function delete($id){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $afterSaleModel = new AfterSale();
        $res = $afterSaleModel->aftersaleDelete($id);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '删除失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '删除成功';
        return $this->return_result($this->returnData);
    }
}
